package com.itcast.dao.impl;

import java.util.List;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.orm.hibernate4.support.HibernateDaoSupport;

import com.itcast.dao.DbInfoDao;
import com.itcast.domain.DbInfo;

public class DbInfoDaoImpl extends HibernateDaoSupport implements DbInfoDao{
	
	 private JdbcTemplate jdbcTemplate;  
     
	    public JdbcTemplate getJdbcTemplate() {  
	        return jdbcTemplate;  
	    }  
	     
	    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {  
	        this.jdbcTemplate = jdbcTemplate;  
	    }  

	@Override
	public void save(DbInfo dbInfo) {
		this.getHibernateTemplate().save(dbInfo);
	}

	@Override
	public void update(DbInfo dbInfo) {
		this.getHibernateTemplate().update(dbInfo);
	}

	@Override
	public void delete(DbInfo dbInfo) {
		this.getHibernateTemplate().delete(dbInfo);
	}

	@Override
	public List<DbInfo> findById(Integer db_id) {
		String sql = "select * from user_has_db where db_id = ? ;";
		RowMapper<DbInfo> rowMapper = BeanPropertyRowMapper.newInstance(DbInfo.class);
		return (List<DbInfo>) this.jdbcTemplate.query(sql, rowMapper,db_id);
	}

	@Override
	public List<DbInfo> findByOwner(Integer owner_id,int pageIndex) {
		String sql = "select * from user_has_db where owner_id = ?  order by db_id LIMIT ?,?;";
		RowMapper<DbInfo> rowMapper = BeanPropertyRowMapper.newInstance(DbInfo.class);
		return (List<DbInfo>) this.jdbcTemplate.query(sql, rowMapper,owner_id,(pageIndex - 1) * 30,pageIndex * 30);
	}

	@Override
	public List<DbInfo> findByNew(Integer owner_id, String dbname) {
		String sql = "select * from user_has_db where db_id = (select max(db_id) from user_has_db where owner_id = ? and dbname = ?)";
		RowMapper<DbInfo> rowMapper = BeanPropertyRowMapper.newInstance(DbInfo.class);
		return (List<DbInfo>) this.jdbcTemplate.query(sql, rowMapper,owner_id,dbname);
	}

}
